/*
 * Copyright 2011 David de Mingo
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package org.shalma.internal.client;

import org.shalma.client.view.View;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Document;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.PushButton;
import com.google.gwt.user.client.ui.Widget;

public class LoginView extends View {

	interface Binder extends UiBinder<Widget, LoginView> {
	}

	private static Binder binder = GWT.create(Binder.class);

	@UiField
	FlowPanel panel;

	@UiField
	public Style style;

	public LoginView() {

		initWidget(binder.createAndBindUi(this));

		addProvider("google.com/accounts/o8/id", LoginIcons.instance.google());
		// addProvider("yahoo.com", LoginIcons.instance.yahoo());
		// addProvider("myopenid.com", LoginIcons.instance.myOpenId());
	}

	@Override
	public void onShow() {
	}

	void addProvider(String id, ImageResource icon) {

		final String href = createLoginUrl(id);

		PushButton button = new PushButton(new Image(icon));
		button.addStyleName(style.link());
		button.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {

				// if (Utils.isMobile()) {
				Window.Location.assign(href);
				// } else {
				// Window.open(href, "openid_popup", "width=790,height=580");
				// }
			}
		});

		panel.add(button);
	}

	private String createLoginUrl(String id) {

		final StringBuilder href = new StringBuilder();

		// TODO no return to #login
		if (GWT.isProdMode()) {
			href.append(GWT.getHostPageBaseURL());
			href.append("_ah/login_redir?claimid=");
			href.append(id);
			href.append("&continue=");
			href.append(Document.get().getURL());

		} else {
			// href.append("/_ah/login?continue=/openid_return_to");
			href.append("/_ah/login?continue=/?gwt.codesvr=127.0.0.1:9997#"
					+ Shell.ME_TOKEN);
		}

		return href.toString();
	}

	interface Style extends CssResource {

		String link();
	}
}
